package win.doyto.service.data.report;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.AbstractView;
import win.doyto.service.data.config.ReportConfigEntity;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static win.doyto.service.data.report.ReportController.*;

/**
 * AbstractReportView
 *
 * @author f0rb on 2017-12-20.
 */
public class AbstractReportView extends AbstractView {

    private static final Map<String, View> viewMap = new HashMap<>();

    ReportService reportService;

    public AbstractReportView(ReportService reportService, String contentType) {
        this.reportService = reportService;
        super.setContentType(contentType);
        viewMap.put(reportService.getExtension(), this);
    }

    @Override
    @SuppressWarnings("unchecked")
    protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<ReportConfigEntity> reportConfigEntities = (List<ReportConfigEntity>) model.get(KEY_REPORT_CONFIG_LIST);
        String suffix = (String) model.get(KEY_SUFFIX);
        Map<String, Object> params = (Map<String, Object>) model.get(KEY_PARAMS);
        String filename;
        if (!reportConfigEntities.isEmpty()) {
            filename = reportConfigEntities.get(0).getReportName();
            if (StringUtils.isNotBlank(suffix)) {
                //文件名格式化
                filename = filename.replace("%D", DateFormatUtils.format(new Date(), "yyyyMMdd"));
                if (model.containsKey("title") && filename.contains("%title%")) {
                    filename = filename.replace("%title%", model.get("title").toString());
                }
                configFilename(request, response, filename, suffix);
            }
        }
        response.setContentType(getContentType());
        reportService.fetchAndWrite(response.getOutputStream(), reportConfigEntities, params);

    }

    public static View chooseViewBySuffix(String suffix) {
        return viewMap.get(suffix);
    }

    public static void configFilename(HttpServletRequest request, HttpServletResponse response, String filename, String suffix) {
        if (!suffix.startsWith(".")) {
            suffix = "." + suffix;
        }
        if (filename != null && filename.length() > 0) {
            if (!filename.endsWith(suffix)) {
                filename = filename + suffix;
            }
            String userAgent = request.getHeader("User-Agent");
            // filename.getBytes("UTF-8")处理safari的乱码问题
            byte[] bytes = userAgent.contains("MSIE") ? filename.getBytes() : filename.getBytes(StandardCharsets.UTF_8);
            // 各浏览器基本都支持ISO编码
            filename = new String(bytes, StandardCharsets.ISO_8859_1);
            // 文件名外的双引号处理firefox的空格截断问题
            response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", filename));
        }
    }
}
